package com.herui.ota.service.iml;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.herui.ota.dao.mysql.DeviceOtaEventMapper;
import com.herui.ota.entity.Device;
import com.herui.ota.entity.DeviceOtaEvent;
import com.herui.ota.enums.OpsTypeEnum;
import com.herui.ota.pojo.vo.DeviceOtaEventChannel;
import com.herui.ota.service.DeviceOtaEventService;
import com.herui.ota.service.OpsRecordService;
import com.mlnx.common.form.PageForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * author name: amanda.shan
 * create time: 2023-10-26 16:51:33
 */ 
@Service
public class DeviceOtaEventServiceIml extends BaseService<DeviceOtaEventMapper, DeviceOtaEvent> implements DeviceOtaEventService{

	@Autowired
	private OpsRecordService opsRecordService;

	@Autowired
	@Override
	public void setBaseMapper(DeviceOtaEventMapper baseMapper) {
		super.setBaseMapper(baseMapper);
	}

	@Override
	public void save(Device device, boolean sucess) {
		DeviceOtaEvent deviceOtaEvent = new DeviceOtaEvent();
		deviceOtaEvent.setDate(new Date());
		deviceOtaEvent.setDeviceId(device.getBluName());
		deviceOtaEvent.setVersion(device.getVersion());
		deviceOtaEvent.setSucess(sucess);
		save(deviceOtaEvent);

		opsRecordService.save(OpsTypeEnum.CREATE_OTA_EVENT, deviceOtaEvent.getId(), JSON.toJSONString(deviceOtaEvent));
	}

	@Override
	public List<DeviceOtaEventChannel> listDeviceOtaEventChannel(String version) {
		List<DeviceOtaEventChannel> deviceOtaEventChannels = baseMapper.listDeviceOtaEventChannel(version);
		AtomicInteger sum = new AtomicInteger();
		deviceOtaEventChannels.forEach(deviceOtaEventChannel -> sum.addAndGet(deviceOtaEventChannel.getCount()));
		deviceOtaEventChannels.forEach(deviceOtaEventChannel -> {
			int count = deviceOtaEventChannel.getCount();
			int i = count * 100 / sum.get();
			deviceOtaEventChannel.setPercent(i/100.0f);
		});
		return deviceOtaEventChannels;
	}

	@Override
	public IPage page(PageForm pageForm, Object filter) throws IllegalAccessException {
		QueryWrapper wrapper = this.getQueryWrapper(filter);
		wrapper.orderByDesc("date");
		return this.page(new Page(pageForm.getCurrent(), pageForm.getSize()), wrapper);
	}
}

